<template>
    <div class="customize-opportunity-page">
    <!-- 返回按钮和页面标题 -->
    <van-nav-bar title="定制商机" left-arrow @click-left="goBack" />
    <!-- 提示信息 -->
    <div class="prompt-section">
        <span class="required">*</span>
        <span>您经营的产品或主营业务是？</span>
    </div>
    <div class="description">
        请输入您的产品或行业关键词（可填写多个,多个换行区分），系统将精准匹配相关的商机信息，每天第一时间推送给您。
    </div>
    <!-- 输入框 -->
    <van-field
        type="textarea"
        v-model="keywords"
        autosize
        placeholder="请输入关键词"
        border-radius="8px"
        style="margin-left:1%;margin-right:1%;width:98%;height:150px;"
    />
    <!-- 字数提示 -->
    <div class="word-count-tip">
        至少填写一个产品名称，两个字以上，{{keywords.length}}/200字
    </div>

    <div style="padding:10px;">接收以下地区的商机：</div>
    <!-- 选择项 -->
    <div style="margin-bottom:200px;">
        <van-grid :column-num="3">
            <van-grid-item
            v-for="(province, index) in provinceList"
            :key="index"
            :text="province.name"
            class="selected-area"
            >
                <van-checkbox v-model="province.checked">{{ province.name }}</van-checkbox>
            </van-grid-item>
        </van-grid>
    </div>
        
    <!-- 提交按钮 -->
    <div style="position:fixed;bottom:0px;left:0px;width:100%;background-color:#f7f7f7;z-index:10001;">
        <van-button type="primary" size="large" style="margin:1%;width:98%;margin-top:20px;" @click="submitKeywords">提交保存</van-button>
        <!-- 客服联系提示 -->
        <div class="contact-客服-tip">
            <van-link type="primary" style="color:rgb(12, 165, 165)" underline @click="contactCustomerService">如有疑问，请点击联系客服</van-link>
        </div>  
    </div>
</div>
</template>

<script>
import { addDzsjinfo, addHyinfo, getAccessToken, getUserInfo, listSysarea, queryDzsjinfoByHyid, querySysConifgByKey } from '@/api/api';
import wechat from '@/utils/wechat';
import { ref } from 'vue';
export default {
    data() {
        return {
            keywords: '',
            hyid:undefined,
            provinceList: [{name:'全国',provincecode:'',checked:ref(false)}],
            hyid:undefined,
        }
    },
    created() {
        this.hyid = localStorage.getItem('hyid') ? localStorage.getItem('hyid'):this.$route.query.hyid
        if(!this.hyid){
            this.getWxopenid()
        }
        // 页面加载时的逻辑
        this.getSysAreaProvinceList()
    },
    methods: {

        getWxopenid(){
            let that = this
            wechat.getOpenId().then(data => {
                let code = data.code
                if (code) {
                    try {
                    let param = {
                        code: code,
                    }
                    getAccessToken(param).then(res => {
                        if(res.code == 200){
                        let access_token = res.data.access_token
                        let openid = res.data.openid
                        that.openid = openid
                        that.accessToken = access_token
                        localStorage.setItem('openid', res.data.openid)
                        localStorage.setItem('accessToken', res.data.access_token)
                        localStorage.setItem('refresh_token', res.data.refresh_token)
                        let data2 = {
                            openid: openid,
                            access_token: access_token
                        }
                        getUserInfo(data2).then(res1 => {
                            if(res1.code == 200){
                            data2 = res1.data
                            that.saveHyinfoByOpenid(data2);
                            }
                        })
                        }
                    })
                    } catch (error) {
                    console.error('获取失败:', error);
                    }
                }
            })
            .catch(error => {
                debugger
                console.error('获取失败:', error)
            })
        },

        // 保存会员信息
        saveHyinfoByOpenid(param){
            let that = this
            param.wxname = param.nickname
            addHyinfo(param).then(response => {
                if(response.code == 200){
                    that.hyid = response.data.hyid
                    that.zhye = response.data.zhye
                    localStorage.setItem('wxname', response.data.wxname)
                    localStorage.setItem('zhye', response.data.zhye)
                    localStorage.setItem('hyid', that.hyid)
                }else{
                    debugger
                    console.log('添加失败:', response)
                }
            })
        },

        queryDzsjinfoByHyid(){
            let that = this 
            const param = { hyid: this.hyid }
            queryDzsjinfoByHyid(param).then(res => {
                if (res.code == 200) {
                    that.keywords = res.data.content
                    let provincecodes = res.data.provincecodes 
                    if(provincecodes){
                        let subList = provincecodes.split(',')
                        let provinceList = that.provinceList;
                        for(var i=0;i<provinceList.length;i++){
                            provinceList[i].checked = false
                            that.$set(that.provinceList, i, provinceList[i])
                            for(var j=0;j<subList.length;j++){
                                if(provinceList[i].code == subList[j]){
                                    provinceList[i].checked = true
                                }
                            }
                        }
                        that.provinceList = provinceList
                    }
                }
            })
        },
        getSysAreaProvinceList() {
            const param = { level: 1 }
            listSysarea(param).then(response => {
                if(response.code == 200){
                    let list = response.rows
                    for(var i=0;i<list.length;i++){
                        list[i].checked = false
                    }
                    this.provinceList = this.provinceList.concat(list)
                    this.queryDzsjinfoByHyid()
                }
            })
        },
        goBack() {
            // 处理返回上一页逻辑，比如使用路由返回
            this.$router.back()
        },
        submitKeywords() {
            let list = this.provinceList
            let subList = []
            if(list && list.length >0 ){
                for(var i=0;i<list.length;i++){
                    if(list[i].checked){
                        subList.push(list[i].code)
                    }
                }
            }
            let param = {content:this.keywords,hyid:this.hyid}
            param.provincecodes = subList.toString()
            addDzsjinfo(param).then(res => {
                if(res.code == 200){
                    this.$toast('保存成功')
                    this.$router.push({
                        path: '/sjinfolist',
                    })
                }
            })
        },
        contactCustomerService() {
            // 处理联系客服逻辑，比如跳转到客服页面或拨打电话
            querySysConifgByKey({ configKey: 'khphone' }).then(res => {
                if (res.code == 200) {
                window.location.href = 'tel:' + res.data
                }
            })
        }
    }
}
</script>

<style scoped>
.customize-opportunity-page {
    background-color: #f7f7f7;
}
.prompt-section {
    display: flex;
    align-items: center;
    font-size: 14px;
    padding:5px;
}
.required {
    color: red;
    margin-right: 5px;
}
.description {
    color: #666;
    margin-bottom: 10px;
    font-size: 14px;
    padding-left:10px;
    padding-right: 10px;
    line-height: 1.5;
}
.word-count-tip {
    color: #999;
    text-align: right;
    margin-top: 5px;
    font-size: 12px;
    margin-right: 10px;
}
.contact-客服-tip {
    text-align: center;
    margin-top: 20px;
    margin-bottom: 20px;
}

.selected-area {
    background-color: #f0faff;
    color: #07c160;
}

</style>
